package gdufs.stat.service;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import gdufs.stat.service.vo.Bill;

import org.apache.commons.lang.time.DateUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;

public class BillQuery {

	Log logger = LogFactory.getLog(BillQuery.class);
	
	private JdbcTemplate jdbcTemplate;
	
	public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
		this.jdbcTemplate = jdbcTemplate;
	}
	
	public Bill queryBill(String userId){
		Calendar calendar = Calendar.getInstance();
		calendar.add(Calendar.DATE, -1);
		DateUtils.truncate(calendar, Calendar.DATE);
		
		final Bill bill = new Bill();
		bill.setUserId(userId);
		bill.setEndTime(calendar.getTime());
		
		
		List result = jdbcTemplate.query("select KPZT as status,RXFXE as remainder from usr_datai.t_ykt_kh where SFRZH=?", new String[]{userId}, new RowMapper(){

			public Object mapRow(ResultSet rs, int arg1) throws SQLException {
				bill.setStatus(rs.getString("status"));
				bill.setRemainder(rs.getFloat("remainder")/100f);
				return null;
			}});
		if(result.size()>0){
			Date today = DateUtils.truncate(new Date(), Calendar.DATE);
			Date yesterday = calendar.getTime();
			yesterday = DateUtils.truncate(yesterday, Calendar.DATE);
			logger.debug("yesterday:"+yesterday);
			float yesterdayAmount = getPeriodAmount(bill, yesterday, today);
			bill.setYesterdayAmount(yesterdayAmount);
			
			calendar = Calendar.getInstance();
			calendar.add(Calendar.WEEK_OF_MONTH, -1);
			Date lastWeek = calendar.getTime();
			lastWeek = DateUtils.truncate(lastWeek, Calendar.DATE);
			logger.debug("lastWeek:"+lastWeek);
			float lastWeekAmount = getPeriodAmount(bill, lastWeek, today);
			bill.setLastWeekAmount(lastWeekAmount);
		}
		return bill;
	}

	private float getPeriodAmount(final Bill bill,
			Date yesterday, Date today) {
		return (Float)jdbcTemplate.queryForObject("select sum(jyje) as amount from usr_datai.t_ykt_grjy where SFRZH=? and to_date(jyrq,'yyyy-mm-dd hh24:mi:ss')>? and to_date(jyrq,'yyyy-mm-dd hh24:mi:ss')<? and jyje like '-%'",
				new Object[]{bill.getUserId(),yesterday,today}, 
				new RowMapper(){
	
					public Object mapRow(ResultSet rs, int arg1) throws SQLException {
					
						return Math.abs(rs.getFloat("amount")/100f);
					}
				});
	}

	
}
